import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/home/index.vue'

Vue.use(VueRouter)
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: '/home',
    meta: {
      //只要在其中一个路由加了，其他都要加
      needLogin: false
    }
  },
  {
    path: '/home',
    name: "Home",
    component: Home,
    meta: {
      needLogin: false
    }
  },
  {
    path: '/detail/=:id',
    name: "Detail",
    component: () =>
      import("../views/detail/index.vue"),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/cate',
    name: "Cate",
    component: () =>
      import("../views/cate/index.vue"),
    meta: {
      needLogin: false
    },
    children: [
      {
        path: 'sub',
        name: "subCate",
        component: () =>
          import("../views/cate/subCate/index.vue"),
        meta: {
          needLogin: false
        }
      }
    ]
  },
  {
    path: '/cart',
    name: "Cart",
    component: () =>
      import("../views/cart/index.vue"), //懒加载
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user',
    name: "User",
    component: () =>
      import("../views/user/index.vue"),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/login',
    name: "Login",
    component: () =>
      import("../views/login/index.vue"),
    meta: {
      needLogin: false
    }
  },
  {
    path: '*',
    name: "NotFound",
    component: () =>
      import("../views/notFound/index.vue"),
    meta: {
      needLogin: false
    }
  },

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to ==> 即将进入的路由
  // from ===》离开的路由
  // console.log(to,"to -----");
  // console.log(from, "from -----");
  // 先判断即将进入的路由，他是不是需要登录
  if (to.meta.needLogin) {
    // alert("login")
    // 条件为真时，需要登录
    // 在登录的一瞬间，设置了一个缓存 点击登录按钮  存入token
    // localStorage.set(token,"wqdejfnisfieffurn")
    if (localStorage.getItem('token')) {
      //判断是否登录过
      next()
    } else {
      next({
        path: '/login',
        query: {
          from: from.fullPath
        }
      })
    }  
  } else {
    next()
  }
  // next() ==》 放行函数必须有
  // next()
})

export default router
